import Win from './Win.js';
import Util from '../Util.js';
import TaskBar from './TaskBar.js';
import Http from './Http.js';
import Msg from './Message.js';

export default class Mouse {
    constructor() { }

    /**
     * 接收数据源作为参数
     * 
     * @static
     * @param {*} desktop
     * @memberof Mouse
     */
    static rightKey(desktop) {

        function setPos(event, rightKeyMenu) {
            const rightMenuCtrl = document.querySelector('#rightMenuCtrl');

            // 用控件触发css样式，方便css自动取消
            rightMenuCtrl.checked = true;

            // 对弹出位置进行限制，不能超出窗口
            // 对最终位置增减1像素，避免菜单弹出后挡住鼠标
            if (rightKeyMenu.offsetHeight + event.clientY > window.innerHeight && rightKeyMenu.offsetWidth + event.clientX < window.innerWidth) {
                rightKeyMenu.setAttribute('style', `left: ${event.clientX + 1}px; top: ${event.clientY - rightKeyMenu.offsetHeight + 1}px;`);
            } else if (rightKeyMenu.offsetWidth + event.clientX > window.innerWidth && rightKeyMenu.offsetHeight + event.clientY < window.innerHeight) {
                rightKeyMenu.setAttribute('style', `left: ${window.innerWidth - rightKeyMenu.offsetWidth - 1}px; top: ${event.clientY + 1}px;`);
            } else if (rightKeyMenu.offsetHeight + event.clientY > window.innerHeight && rightKeyMenu.offsetWidth + event.clientX > window.innerWidth) {
                rightKeyMenu.setAttribute('style', `left: ${window.innerWidth - rightKeyMenu.offsetWidth - 1}px; top: ${event.clientY - rightKeyMenu.offsetHeight - 1}px;`);
            } else {
                rightKeyMenu.setAttribute('style', `left: ${event.clientX + 1}px; top: ${event.clientY + 1}px;`);
            }
        }

        function buildDpMenu(id) {
            const rightKeyMenu = document.createElement('div');

            let isFullScreen = Util.isFullscreenForNoScroll();
            let isOnTaskBar = TaskBar.isOnTaskBar(id);
            let isOn = Win.isOn(desktop, id);

            rightKeyMenu.className = 'right-key-menu';
            rightKeyMenu.innerHTML = `
                <ul id="rightKeyMenu_${id}">
                    <li style="background-image: url(${desktop.app[id].icon})" data-function="${isOn ? 'close' : 'open'}">${isOn ? '关闭' : '打开'}${desktop.app[id].name}</li>
                    <hr>
                    <li style="background-image: url(./images/system/${isOnTaskBar ? 'not-pin.png' : 'pin.png'})" data-function="${isOnTaskBar ? 'removeFromTaskBar' : 'fixToTaskBar'}">${isOnTaskBar ? '从任务栏取消固定' : '固定到任务栏'}</li>
                    <li data-function="fixToStart">固定到开始屏幕(未完成)</li>
                    <li data-function="refresh" style="background-image: url(./images/system/refresh.webp)">刷新</li>
                    <li style="background-image: url(./images/system/bug.png)" data-function="${isFullScreen ? 'exitFullScreen' : 'fullScreen'}">${isFullScreen ? '退出' : '开启'}全屏模式</li>
                    <hr>
                    <li style="background-image: url(./images/system/logout.png)" data-function="logout">退出登录</li>
                    <li>疑难解答(未完成)</li>
                    <li data-function="backToDefault" style="background-image: url(./images/system/danger.png)">初始化</li>
                    <li>关于(未完成)</li>
                    <hr>
                    <li data-function="delete" style="background-image: url(./images/system/delete.png)">删除</li>
                </ul>
            `;
            document.body.appendChild(rightKeyMenu);

            // 添加事件
            document.getElementById(`rightKeyMenu_${id}`).addEventListener('click', function (event) {
                const type = event.target.getAttribute('data-function');
                if (type === 'open') {
                    Win.open(desktop, id);
                } else if (type === 'close') {
                    Win.close(id);
                } else if (type === 'fixToTaskBar') {
                    TaskBar.fixToTaskBar(desktop, id);
                } else if (type === 'removeFromTaskBar') {
                    TaskBar.removeFromTaskBar(desktop, id);
                } else if (type === 'fixToStart') {
                    // TODO
                } else if (type === 'fullScreen') {
                    Util.launchFullscreen(document.body);
                } else if (type === 'exitFullScreen') {
                    Util.exitFullscreen();
                } else if (type === 'refresh') {
                    window.location.reload();
                } else if (type === 'backToDefault') {
                    const user = JSON.parse(window.localStorage['user']);
                    Http.ajax({
                        url: `/app/${user.name}/restore`,
                        success: function () {
                            window.location.reload();
                        }
                    });
                } else if (type === 'logout') {
                    const user = JSON.parse(window.localStorage['user']);
                    Http.ajax({
                        url: `/logout`,
                        data: JSON.stringify({
                            name: user.name,
                            password: ''
                        }),
                        success: function () {
                            window.location.href = '/html/login.html';
                        }
                    });
                } else if (type === 'delete') {

                    if (desktop.app[id].projectName === 'AppStore') {
                        desktop.focus();
                        new Msg(desktop.app[id], `无法删除${desktop.app[id].name}！`);
                        return;
                    }

                    if (Win.isOn(desktop, id)) {
                        desktop.focus();
                        new Msg(desktop.app[id], `窗口占用中，请关闭[${desktop.app[id].name}]窗口后再试！`);
                        return;
                    }

                    Http.ajax({
                        url: `/app/${JSON.parse(window.localStorage.user).name}/deleteApp/${id}`,
                        success: function () {
                            desktop.deleteApp(id);
                        }
                    });
                }

                this.parentElement.remove();
            });

            return rightKeyMenu;
        }

        window.oncontextmenu = (event) => {

            // 获取元素的自定义属性，包含数据的键值
            const idFormDpIcon = event.target.getAttribute('data-icon-pos');
            const idFromTaskBar = event.target.getAttribute('data-taskbar');

            // 通过键值从数据中找到对象
            // 点击的是桌面图标
            if (idFormDpIcon && typeof desktop.app[idFormDpIcon] !== 'undefined') {
                // 点击图标才有自定义菜单，阻止默认右键菜单
                event.preventDefault();

                let rightKeyMenu = document.getElementsByClassName('right-key-menu')[0];

                // 只创建一次右键菜单，之后都是修改数据，不重新创建
                if (rightKeyMenu) {
                    rightKeyMenu.remove();
                    setPos(event, buildDpMenu(idFormDpIcon));
                } else {
                    setPos(event, buildDpMenu(idFormDpIcon));
                }
                // 依次从数据中对比判断
            } else if (idFromTaskBar) {
                event.preventDefault();
                let rightKeyMenu = document.getElementsByClassName('right-key-menu')[0];

                // 只创建一次右键菜单，之后都是修改数据，不重新创建
                if (rightKeyMenu) {
                    rightKeyMenu.remove();
                    setPos(event, buildDpMenu(idFromTaskBar));
                } else {
                    setPos(event, buildDpMenu(idFromTaskBar));
                }
            } else {
                // 不是特有信息，清除右键菜单
                desktop.focus();
            }
        }
    }
}